<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="icon" href="../../logo.svg" />
    <title>列表排序</title>
  </head>
  <body>
    <div id="root">
      <h2>人员列表</h2>
      <div>
        <input type="text" v-model="keyword" />
        <button @click="sort=1">年龄升序</button>
        <button @click="sort=2">年龄降序</button>
        <button @click="sort=0">原始排序</button>
      </div>
      <ul>
        <li v-for="p in filterPersons" :key="p.id">
          {{p.name}} - {{p.age}} -- {{p.gender}}
        </li>
      </ul>
    </div>

    <script src="../../vue.js"></script>
    <script>
      Vue.config.productionTip = false; // 阻止 vue 在启动时生成生产提示。

      new Vue({
        el: "#root",
        data: {
          persons: [
            { id: 1, name: "马冬梅", age: 12, gender: "女" },
            { id: 2, name: "周冬雨", age: 19, gender: "女" },
            { id: 3, name: "周杰伦", age: 18, gender: "男" },
            { id: 4, name: "温兆伦", age: 41, gender: "男" },
          ],
          keyword: "",
          sort: 0,
        },
        computed: {
          filterPersons() {
            const fps = this.persons.filter(
              (p) => p.name.indexOf(this.keyword) >= 0
            );

            if (this.sort === 0) {
              return fps;
            }

            return fps.sort((a, b) =>
              this.sort === 1 ? a.age - b.age : b.age - a.age
            );
          },
        },
      });
    </script>
  </body>
</html>
